<template>
  <div class="meeting-form">
    <!-- 头部 -->
    <div class="form-header">
      <h2>会议预定申请</h2>
    </div>

    <!-- 表单主体 -->
    <el-form :model="formRules" label-width="80px" label-position="left">
      <!-- 基本信息 -->
      <div class="form-row">
        <el-form-item label="姓名">
          <el-input v-model="form.name"  readonly />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="form.department"  readonly />
        </el-form-item>
      </div>

      <!-- 时间选择 -->
      <div class="form-row">
        <el-form-item label="开始时间" prop="createTime" required>
          <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="请选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" required>
          <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </div>

      <!-- 会议室和参会人 -->
      <div class="form-row">
        <el-form-item label="会议室" prop="meetingRoom" required>
          <el-select v-model="form.meetingRoom" placeholder="请选择会议室">
            <el-option
                v-for="room in meetingRoom"
                :key="room.value"
                :label="room.label"
                :value="room.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参会人员" prop="memberArr" required>
          <el-select
              v-model="memberArr"
              multiple
              placeholder="请选择参会人员"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.name"
                :value="user.name"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- 会议描述 -->
      <el-form-item label="会议描述" required>
        <el-input
            v-model="form.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入会议描述"
            maxlength="500"
            show-word-limit
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="saveDraft">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-form>

  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";

// 表单数据
const form = ref({
  name: getUser().username,
  department: '产品设计部',
    createTime: '',
  endTime: '',
  meetingRoom: '',
  members: '',
  remark: ''
})
const memberArr = ref([]);

//开始时间不得早于当前时间
const validateCreateTime = (rule, value, callback)=>{
    if(value && new Date(value) >= new Date()){
        callback();
    }else{
        form.value.createTime='';
        callback(new Error('开始时间不得早于当前时间'));
    }
}
//结束时间不得早于开始时间
const validateEndTime = (rule, value, callback)=>{
    if(form.value.createTime){
        if(value && new Date(value) >= new Date(form.value.createTime)){
            //验证通过
            callback();
        }else{
            callback(new Error('结束时间不得早于开始时间'));
        }
    }else{
        form.value.endTime='';
        callback(new Error('请先填写开始时间'));
    }
}
//定义校验规则，因为表单是使用reactive动态提交，change就会被触发
const formRules = {
    meetingRoom: [{ required: true, message: '会议室是必填项', trigger: 'change' }],
    createTime: [{ required: true, message: '开始时间是必填项', trigger: 'change' },
        {validator: validateCreateTime, trigger: "change"}],
    endTime: [{ required: true, message: '结束时间是必填项', trigger: 'change' },
        {validator: validateEndTime, trigger: "change"}],
    memberArr:[{ required: true, message: '参会人员是必填项', trigger: 'change' }]
}

// 会议室选项
const meetingRoom = ref([
  { value: 'room-101', label: '第一会议室（10人）' },
  { value: 'room-201', label: 'VIP会议室（20人）' },
  { value: 'room-301', label: '多功能厅（50人）' }
])

// todo 应该遍历该公司的所有人员，选择要参会的人
// 用户列表
const userList = ref([]);

//记录是否有草稿
let isDraft = false;
const submitForm = () => {
    form.value.userId = getUser().id;
    form.value.members = memberArr.value.toString();
    let data = qs.stringify(form.value);
    axios.post(BASE_URL + '/v1/administration/meeting?'+data)
        .then((response)=>{
            if(response.data.code == 2000){
                localStorage.removeItem("meetingDraftMsg");
                localStorage.removeItem("meetingIsDraft");
                isDraft = false;
                window.history.back();
            }else {
                ElMessage.error("会议室申请失败")
            }

        })
}

const saveDraft = () => {
    isDraft = true;
    localStorage.setItem("meetingDraftMsg",JSON.stringify(form.value));
    localStorage.setItem("meetingIsDraft",JSON.stringify(isDraft));
    window.history.back();
}

const goBack = () => {
  window.history.back()
}
//查询所有的员工
const allStaff = ()=>{
    axios.get(BASE_URL+'/v1/personnel/select')
        .then((response)=>{
            if(response.data.code == 2000){
                console.log(response.data)
                userList.value = response.data.data;
            }else {
                ElMessage.error("员工获取失败")
            }

        })
}

onMounted(()=>{
    allStaff();
    //判断是否有该字段，并是否为true
    if(localStorage.getItem("meetingIsDraft")){
        form.value =  JSON.parse(localStorage.meetingDraftMsg)
    }
})
</script>

<style scoped>
.meeting-form {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.form-header {
  margin-bottom: 24px;
  border-bottom: 1px solid #eee;
}

.sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.draft-time {
  color: #666;
  font-size: 14px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 32px;
  text-align: right;
}

.flow-image {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #eee;
}

:deep(.el-form-item__label)::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

:deep(.el-button.is-link) {
  color: #1a5cff;
}

:deep(.el-select) {
  width: 100%;
}
</style>